<template>
	<!-- 核销页面 -->
	<view>
		<view class="one" v-if="isTrue">
			<view class="reuqrcode">
				<view>订单编号：<text>{{ orderId }}</text></view>
				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="orderId" @complete="complete"></uqrcode>
				<view class="code-text">
					请前往指定区域扫码核销
				</view>
			</view>
		</view>

		<view v-else>
			<!-- 二维码失效，请重新生成 -->
			<view class="zz">二维码失效，请重新生成</view>
			<view class="notice">
				<button @click="remake">重新生成</button>
			</view>
		</view>
	</view>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
	data() {
		return {
			orderId: '',
			timer: null,
			isTrue: true,
		}
	},
	onLoad(options) {
		this.orderId = options.orderid;
	},
	methods: {
		...mapMutations('goods', ['clearHxOrderList', 'setPrinterOrderList']),
		complete() { // 二维码生成完成
			this.startPolling(); // 开始轮询
			// 倒计时3分钟，如果超过3分钟，则二维码失效，需要重新生成
			setTimeout(() => {
				this.isTrue = false;
				clearInterval(this.timer);
			}, 1000 * 60 * 3);
		},
		remake() {
			this.isTrue = true;
			this.$refs.uqrcode.make();
		},
		startPolling() {
			this.timer = setInterval(() => {
				this.$ajax.get('orders/checkOrderStatus?orderId=' + this.orderId).then(res => {
					if (res.success) {
						if (res.result) {
							this.setPrinterOrderList(res.result);
							// 清除定时器
							// 跳转到小票页面
							return uni.navigateTo({
								url: '/pages/product/printer'
							})
						}

					}
				})
			}, 2000) // 每2秒轮询一次
		}
	},
	beforeDestroy() {
		clearInterval(this.timer);
	},
	onHide() {
		clearInterval(this.timer);
	}
}
</script>

<style lang="scss" scoped>
.one {
	padding: 20px;
}

.reuqrcode {
	margin-top: 17rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;

}

.code-text {
	font-size: 18px;
	color: #888;
	margin-top: 30rpx;
}

.twocode {
	margin-bottom: 30px;
}

.code {
	text-align: center;
	background-color: #f4f4f4;
	padding: 20px 0;
}

.zz {
	margin-top: 30px;
	border: 1px solid #888;
	display: inline-block;
	margin-left: 50%;
	transform: translateX(-50%);
	padding: 5px 50px;
	font-size: 14px;
}

.notice {
	font-size: 12px;
	line-height: 20px;
	background-color: #f4f4f4;
	margin-top: 30px;
	padding: 10px;
}
</style>